import Vue from 'vue'
import Router from 'vue-router'
import { MessageBox } from 'mint-ui'
import services, {findService} from '../common/js/service_list'
import {STORAGE_TYPE} from '../common/js/config'
import store from '../store'
import {asyncLoad} from '../common/js/async_load'

Vue.use(Router)

// 路由组件懒加载,每个路由组件单独生成一个js,需要时通过创建script标签引入,需要配置webpack的output.chunkFilename
// import(url)返回的是一个Promise对象实例
const home = asyncLoad(() => import('../routes/home/index.vue'))
const service = asyncLoad(() => import('../routes/service/index.vue')) // 办事大厅
const serviceMore = asyncLoad(() => import('../routes/service-more/index.vue')) // 办事大厅（更多服务）
const news = asyncLoad(() => import('../routes/news/index.vue'))
const user = asyncLoad(() => import('../routes/user/index.vue')) // 用户中心
const avatar = asyncLoad(() => import('../routes/avatar/index.vue')) // 修改头像
const userLogin = asyncLoad(() => import('../routes/user-login/index.vue')) // 用户登录
const userCode = asyncLoad(() => import('../routes/user-login-code/index.vue')) // 用户验证码登录
const userRegister = asyncLoad(() => import('../routes/user-register/user-register.vue')) // 用户注册
const userRegisterAgreement = asyncLoad(() => import('../routes/user-register/agreement.vue')) // 用户注册
const apply1 = asyncLoad(() => import('../routes/record/apply/apply-1.vue')) // 申请商调函1
const apply2 = asyncLoad(() => import('../routes/record/apply/apply-2.vue')) // 申请商调函2
const apply3 = asyncLoad(() => import('../routes/record/apply/apply-3.vue')) // 申请商调函3
const apply4 = asyncLoad(() => import('../routes/record/apply/apply-4.vue')) // 申请商调函4
const applySuccess = asyncLoad(() => import('../routes/record/apply/apply-success.vue')) // 申请商调函成功
const query = asyncLoad(() => import('../routes/record/query/query.vue')) // 档案查询（表单）
const queryList = asyncLoad(() => import('../routes/record/query/query-list.vue')) // 档案查询（结果）（办事大厅）
const recordTransfer = asyncLoad(() => import('../routes/record/transfer/transfer.vue')) // 档案转出
const certify = asyncLoad(() => import('../routes/record/certify/certify.vue')) // 档案开具证明
const borrow = asyncLoad(() => import('../routes/record/borrow/borrow.vue')) // 档案借出
const rollIn1 = asyncLoad(() => import('../routes/party/roll-in/roll-in-1.vue')) // 党员组织关系转入1
const rollIn2 = asyncLoad(() => import('../routes/party/roll-in/roll-in-2.vue')) // 党员组织关系转入2
const rollIn3 = asyncLoad(() => import('../routes/party/roll-in/roll-in-3.vue')) // 党员组织关系转入3
const rollIn4 = asyncLoad(() => import('../routes/party/roll-in/roll-in-4.vue')) // 党员组织关系转入4
const rollIn5 = asyncLoad(() => import('../routes/party/roll-in/roll-in-5.vue')) // 党员组织关系转入5
const rollInSuccess = asyncLoad(() => import('../routes/party/roll-in/success.vue')) // 党员组织关系转入（结果页）
const pay = asyncLoad(() => import('../routes/party/pay/pay.vue')) // 党员缴费
const payWay = asyncLoad(() => import('../routes/party/pay/pay-way.vue')) // 党员缴费（选择支付方式）
const paySuccess = asyncLoad(() => import('../routes/party/pay/success.vue')) // 党员缴费（缴费成功）
const payWaiting = asyncLoad(() => import('../routes/party/pay/waiting.vue')) // 党员缴费（待支付）
const payRecord = asyncLoad(() => import('../routes/party/pay/pay-record.vue')) // 党员缴费（缴费记录）
const activities = asyncLoad(() => import('../routes/party/activity/activity-list.vue')) // 党员报名列表
const activity = asyncLoad(() => import('../routes/party/activity/activity.vue')) // 党员报名详情
const activityForm = asyncLoad(() => import('../routes/party/activity/activity-form.vue')) // 党员活动报名（表单）
const activitySuccess = asyncLoad(() => import('../routes/party/activity/success.vue')) // 党员活动报名成功
const activityInfo = asyncLoad(() => import('../routes/party/activity/activity-info.vue')) // 党员报名信息
const datumNeed = asyncLoad(() => import('../routes/datum-need/index.vue')) // 所需材料
const residenceSearch = asyncLoad(() => import('../routes/residence/search/search.vue')) // 户口查询
const residenceIn = asyncLoad(() => import('../routes/residence/in/in.vue')) // 户籍关系转入
const residenceOut = asyncLoad(() => import('../routes/residence/out/out.vue')) // 户籍关系转出
const medical1 = asyncLoad(() => import('../routes/residence/medical/medical-1.vue')) // 省医疗保险办理
const medical2 = asyncLoad(() => import('../routes/residence/medical/medical-2.vue')) // 市养老、医疗保险办理
const securityQuery = asyncLoad(() => import('../routes/residence/query/query.vue')) // 社保查询
const modify = asyncLoad(() => import('../routes/residence/modify/modify.vue')) // 养老缴费基数变更
const title1 = asyncLoad(() => import('../routes/residence/title/title-1.vue')) // 职称申报1
const title2 = asyncLoad(() => import('../routes/residence/title/title-2.vue')) // 职称申报2
const titleSuccess = asyncLoad(() => import('../routes/residence/title/success.vue')) // 职称申报（结果）
const education = asyncLoad(() => import('../routes/education/education/education.vue')) // 继续教育个人信息预录入
const agreement = asyncLoad(() => import('../routes/education/education/agreement.vue')) // 继续教育个人信息预录入（用户协议书）
const signUp = asyncLoad(() => import('../routes/education/sign-up/sign-up.vue')) // 继续教育报名
const qualified = asyncLoad(() => import('../routes/education/qualified/qualified.vue')) // 办理合格证明（列表）
const qualifiedInfo = asyncLoad(() => import('../routes/education/qualified/qualified-info.vue')) // 继续教育信息
const qualifiedUpload = asyncLoad(() => import('../routes/education/qualified/qualified-upload.vue')) // 继续教育（上传资料）
const suggest = asyncLoad(() => import('../routes/suggest/suggest.vue')) // 我要说
const praise = asyncLoad(() => import('../routes/suggest/praise.vue')) // 我要表扬表单
const letter = asyncLoad(() => import('../routes/suggest/letter.vue')) // 主任信箱表单
const suggestDetail = asyncLoad(() => import('../routes/suggest/detail.vue')) // 我要说详情
const newsDetail = asyncLoad(() => import('../routes/news/detail.vue')) // 新闻详情
const newsList = asyncLoad(() => import('../routes/news/list.vue')) // 新闻列表
const userInfo = asyncLoad(() => import('../routes/user/info/info.vue')) // 个人基本信息编辑
const username = asyncLoad(() => import('../routes/user/info/name.vue')) // 个人基本信息 用户名编辑
const idCard = asyncLoad(() => import('../routes/user/info/id-card.vue')) // 个人基本信息 身份证号编辑
const sys = asyncLoad(() => import('../routes/user/sys/sys.vue')) // 个人系统设置
const password = asyncLoad(() => import('../routes/user/sys/password.vue')) // 个人系统设置（修改密码）
const binding = asyncLoad(() => import('../routes/user/sys/binding.vue')) // 个人系统设置（绑定管理）
const phone = asyncLoad(() => import('../routes/user/sys/phone.vue')) // 个人系统设置（更换手机号）
const myPay = asyncLoad(() => import('../routes/user/my-pay/my-pay.vue')) // 我的缴费列表
const myApply = asyncLoad(() => import('../routes/user/my-apply/my-apply.vue')) // 我的办理列表
const myApplyDetail = asyncLoad(() => import('../routes/user/my-apply/detail.vue')) // 我的办理详情
const myBook = asyncLoad(() => import('../routes/user/my-book/my-book.vue')) // 我的预约列表
const myBookDetail = asyncLoad(() => import('../routes/user/my-book/detail.vue')) // 我的预约详情
const myFile = asyncLoad(() => import('../routes/user/my-file/my-file.vue')) // 我的档案
const cert = asyncLoad(() => import('../routes/user/cert/cert.vue')) // 高级认证
const message = asyncLoad(() => import('../routes/user/message/message.vue')) // 站内信
const corpMessage = asyncLoad(() => import('../routes/corp/message/message.vue')) // 站内信（单位）
const mySuggest = asyncLoad(() => import('../routes/user/my-suggest/my-suggest.vue')) // 我的反馈
const myLetter = asyncLoad(() => import('../routes/user/my-letter/my-letter.vue')) // 个人中心-主任信箱
const corpLogin = asyncLoad(() => import('../routes/corp-login/index.vue')) // 单位登录
const corp = asyncLoad(() => import('../routes/corp/index.vue')) // 单位中心
const corpHome = asyncLoad(() => import('../routes/corp-home/index.vue')) // 单位首页
const corpQuery = asyncLoad(() => import('../routes/corp/corp-query/corp-query.vue')) // 综合查询
const corpQuerySearch = asyncLoad(() => import('../routes/corp/corp-query/search.vue')) // 综合查询（弹出查询）
const corpQueryDetail = asyncLoad(() => import('../routes/corp/corp-query/detail.vue')) // 综合查询（详情）
const corpInfo = asyncLoad(() => import('../routes/corp/info/info.vue')) // 单位信息修改
const corpInfoName = asyncLoad(() => import('../routes/corp/info/name.vue')) // 单位名称修改
const corpInfoNumber = asyncLoad(() => import('../routes/corp/info/number.vue')) // 单位组织机构代码修改
const test = asyncLoad(() => import('../routes/test/index.vue')) // 测试页面1
const test2 = asyncLoad(() => import('../routes/test/test-s.vue')) // 测试页面2
const test3 = asyncLoad(() => import('../routes/test/test-t.vue')) // 测试页面3
const aboutUs = asyncLoad(() => import('../routes/user/sys/about.vue')) // 关于我们
const reset = asyncLoad(() => import('../routes/user/reset/reset.vue')) // 忘记密码

const router = new Router({
  routes: [{
    name: 'home',
    path: '/home',
    component: home,
    children: [{
      name: 'homeServiceMore',
      path: 'more/:id',
      component: serviceMore
    }, {
      name: 'homeNewsDetail',
      path: 'news',
      component: newsDetail
    }]
  }, {
    name: 'service',
    path: '/service',
    component: service,
    children: [{
      name: 'serviceMore',
      path: 'more/:id',
      component: serviceMore
    }]
  }, {
    name: 'news',
    path: '/news',
    component: news,
    children: [{
      name: 'newsDetail',
      path: 'detail',
      component: newsDetail
    }]
  }, {
    name: 'newsList',
    path: '/news-list/:id',
    component: newsList,
    children: [{
      name: 'newsListDetail',
      path: 'detail',
      component: newsDetail
    }]
  }, {
    name: 'user',
    path: '/user',
    component: user,
    meta: {role: 'user'}
  }, {
    name: 'avatar',
    path: '/avatar',
    component: avatar,
    meta: {role: 'all'}
  }, {
    name: 'userLogin',
    path: '/user-login',
    component: userLogin
  }, {
    name: 'userRegister',
    path: '/user-register',
    component: userRegister,
    children: [{
      name: 'userRegisterAgreement',
      path: 'agreement',
      component: userRegisterAgreement
    }]
  }, {
    name: 'userCode',
    path: '/userCode',
    component: userCode
  }, {
    name: 'apply1',
    path: '/apply-1',
    component: apply1,
    meta: {role: 'user'}
  }, {
    name: 'apply2',
    path: '/apply-2',
    component: apply2,
    meta: {role: 'user'}
  }, {
    name: 'apply3',
    path: '/apply-3',
    component: apply3,
    meta: {role: 'user'}
  }, {
    name: 'apply4',
    path: '/apply-4',
    component: apply4,
    meta: {role: 'user'}
  }, {
    name: 'applySuccess',
    path: '/apply-success',
    component: applySuccess,
    meta: {role: 'user'},
    children: [{
      name: 'applySuccessChild',
      path: 'datum-need',
      component: datumNeed,
      meta: {role: 'user'}
    }]
  }, {
    name: 'query',
    path: '/query',
    component: query
  }, {
    name: 'queryList',
    path: '/query-list',
    component: queryList
  }, {
    name: 'recordTransfer',
    path: '/record-transfer',
    component: recordTransfer,
    meta: {role: 'user', auth: true, file: true}
  }, {
    name: 'certify',
    path: '/certify',
    component: certify,
    meta: {role: 'user', auth: true, file: true}
  }, {
    name: 'borrow',
    path: '/borrow',
    component: borrow,
    meta: {role: 'user'}
  }, {
    name: 'rollIn1',
    path: '/roll-in-1',
    component: rollIn1,
    meta: {role: 'user', auth: true, file: true}
  }, {
    name: 'rollIn2',
    path: '/roll-in-2',
    component: rollIn2,
    meta: {role: 'user'}
  }, {
    name: 'rollIn3',
    path: '/roll-in-3',
    component: rollIn3,
    meta: {role: 'user'}
  }, {
    name: 'rollIn4',
    path: '/roll-in-4',
    component: rollIn4,
    meta: {role: 'user'}
  }, {
    name: 'rollIn5',
    path: '/roll-in-5',
    component: rollIn5,
    meta: {role: 'user'}
  }, {
    name: 'rollInSuccess',
    path: '/roll-in-success',
    component: rollInSuccess,
    meta: {role: 'user'},
    children: [{
      name: 'rollInDatumNeed',
      path: 'datum-need',
      component: datumNeed,
      meta: {role: 'user'}
    }]
  }, {
    name: 'pay',
    path: '/pay',
    component: pay,
    meta: {role: 'user', auth: true}
  }, {
    name: 'payWay',
    path: '/pay-way',
    component: payWay
  }, {
    name: 'paySuccess',
    path: '/pay-success',
    component: paySuccess,
    children: [{
      name: 'normalPayRecord',
      path: 'record',
      component: payRecord
    }]
  }, {
    name: 'payRecord',
    path: '/pay-record',
    component: payRecord
  }, {
    name: 'payWaiting',
    path: '/pay-waiting',
    component: payWaiting
  }, {
    name: 'activities',
    path: '/activities',
    component: activities,
    meta: {role: 'user', auth: true, file: true},
    children: [{
      name: 'activity',
      path: 'activity',
      component: activity,
      meta: {role: 'all'}
    }]
  }, {
    name: 'activityDetail',
    path: '/activity-detail',
    component: activity
  }, {
    name: 'activityForm',
    path: '/activity-form',
    component: activityForm,
    meta: {role: 'user', auth: true},
    children: [{
      name: 'activitySuccess',
      path: 'success',
      component: activitySuccess,
      meta: {role: 'all'}
    }]
  }, {
    name: 'activityInfo',
    path: '/activity-info',
    component: activityInfo,
    meta: {role: 'all'}
  }, {
    name: 'residenceSearch',
    path: '/residence-search',
    component: residenceSearch,
    meta: {role: 'user', auth: true}
  }, {
    name: 'residenceIn',
    path: '/residence-in',
    component: residenceIn,
    meta: {role: 'user', auth: true, file: true},
    children: [{
      name: 'residenceInDatumNeed',
      path: 'datum-need',
      component: datumNeed,
      meta: {role: 'user'}
    }]
  }, {
    name: 'residenceOut',
    path: '/residence-out',
    component: residenceOut,
    meta: {role: 'user', auth: true, file: true},
    children: [{
      name: 'residenceOutDatumNeed',
      path: 'datum-need',
      component: datumNeed,
      meta: {role: 'user'}
    }]
  }, {
    name: 'medical1',
    path: '/medical-1',
    component: medical1,
    meta: {role: 'user', auth: true, file: true},
    children: [{
      name: 'medical1DatumNeed',
      path: 'datum-need',
      component: datumNeed,
      meta: {role: 'user'}
    }]
  }, {
    name: 'medical2',
    path: '/medical-2',
    component: medical2,
    meta: {role: 'user', auth: true, file: true},
    children: [{
      name: 'medical2DatumNeed',
      path: 'datum-need',
      component: datumNeed,
      meta: {role: 'user'}
    }]
  }, {
    name: 'securityQuery',
    path: '/security-query',
    component: securityQuery,
    meta: {role: 'user', auth: true, file: true}
  }, {
    name: 'modify',
    path: '/modify',
    component: modify,
    meta: {role: 'user', auth: true, file: true},
    children: [{
      name: 'modifySecurityQuery',
      path: 'query',
      component: securityQuery,
      meta: {role: 'user'}
    }]
  }, {
    name: 'title',
    path: '/title',
    component: title1,
    meta: {role: 'user', auth: true, file: true}
  }, {
    name: 'title2',
    path: '/title-2',
    component: title2,
    meta: {role: 'user', auth: true}
  }, {
    name: 'titleSuccess',
    path: '/title-success',
    component: titleSuccess,
    meta: {role: 'user', auth: true}
  }, {
    name: 'education',
    path: '/education',
    component: education,
    meta: {role: 'user', auth: true},
    children: [{
      name: 'educationAgreement',
      path: 'agreement',
      component: agreement
    }]
  }, {
    name: 'signUp',
    path: '/sign-up',
    component: signUp,
    meta: {role: 'user', auth: true}
  }, {
    name: 'qualified',
    path: '/qualified',
    component: qualified,
    meta: {role: 'user', auth: true},
    children: [{
      name: 'qualifiedInfo',
      path: 'qualified-info',
      component: qualifiedInfo
    }, {
      name: 'qualifiedUploadChild',
      path: 'upload',
      component: qualifiedUpload
    }]
  }, {
    name: 'qualifiedUpload',
    path: '/qualified-upload',
    component: qualifiedUpload
  }, {
    name: 'suggest',
    path: '/suggest',
    component: suggest,
    children: [{
      name: 'praise',
      path: 'praise',
      component: praise,
      meta: {role: 'all'}
    }, {
      name: 'letter',
      path: 'letter',
      component: letter,
      meta: {role: 'all'}
    }, {
      name: 'suggestDetail',
      path: 'detail',
      component: suggestDetail
    }]
  }, {
    name: 'userInfo',
    path: '/user-info',
    component: userInfo,
    children: [{
      name: 'username',
      path: 'username',
      component: username
    }, {
      name: 'idCard',
      path: 'id-card',
      component: idCard
    }]
  }, {
    name: 'sys',
    path: '/sys',
    component: sys,
    meta: {role: 'all'},
    children: [{
      name: 'password',
      path: 'password',
      component: password
    }, {
      name: 'binding',
      path: 'binding',
      component: binding,
      children: [{
        name: 'phone',
        path: 'phone',
        component: phone
      }]
    }, {
      name: 'about',
      path: 'about',
      component: aboutUs
    }]
  }, {
    name: 'myPay',
    path: '/my-pay/:id',
    component: myPay,
    children: [{
      name: 'myPayWaiting',
      path: 'waiting',
      component: payWaiting
    }, {
      name: 'myPayRecord',
      path: 'record',
      component: payRecord
    }]
  }, {
    name: 'myApply',
    path: '/my-apply/:id',
    component: myApply,
    children: [{
      name: 'myApplyActivitySuccess',
      path: 'activity-success',
      component: activitySuccess,
      children: [{
        name: 'myApplyDetail',
        path: 'detail',
        component: myApplyDetail
      }, {
        // 材料预审类详情
        name: 'myApplyDetail2',
        path: 'detail2',
        component: myBookDetail
      }]
    }]
  }, {
    name: 'myBook',
    path: '/my-book',
    component: myBook,
    children: [{
      name: 'myBookDetail',
      path: 'detail',
      component: myBookDetail
    }]
  }, {
    name: 'myFile',
    path: '/my-file',
    component: myFile,
    meta: {role: 'user', auth: true}
  }, {
    name: 'cert',
    path: '/cert',
    component: cert
  }, {
    name: 'message',
    path: '/message',
    component: message,
    children: [{
      name: 'payRecordMessage',
      path: 'pay-record',
      component: payRecord
    }]
  }, {
    name: 'corpMessage',
    path: '/corp-message',
    component: corpMessage
  }, {
    name: 'mySuggest',
    path: '/my-suggest',
    component: mySuggest,
    children: [{
      name: 'mySuggestDetail',
      path: 'detail',
      component: suggestDetail
    }]
  }, {
    name: 'myLetter',
    path: '/my-letter',
    component: myLetter,
    children: [{
      name: 'myLetterDetail',
      path: 'detail',
      component: suggestDetail
    }]
  }, {
    name: 'corpLogin',
    path: '/corp-login',
    component: corpLogin
  }, {
    name: 'corp',
    path: '/corp',
    component: corp,
    meta: {
      role: 'corp'
    }
  }, {
    name: 'corpHome',
    path: '/corp-home',
    component: corpHome,
    meta: {
      role: 'corp'
    },
    children: [{
      name: 'corpHomeNewsDetail',
      path: 'news',
      component: newsDetail,
      meta: {
        role: 'corp'
      }
    }]
  }, {
    name: 'corpQuery',
    path: '/corp-query',
    component: corpQuery,
    meta: {
      role: 'corp'
    },
    children: [{
      name: 'corpQuerySearch',
      path: 'search',
      component: corpQuerySearch,
      meta: {role: 'corp'}
    }, {
      name: 'corpQueryDetail',
      path: 'detail',
      component: corpQueryDetail,
      meta: {role: 'corp'}
    }]
  }, {
    name: 'corpInfo',
    path: '/corp-info',
    component: corpInfo,
    meta: {role: 'corp'},
    children: [{
      name: 'corpInfoName',
      path: 'name',
      component: corpInfoName,
      meta: {role: 'corp'}
    }, {
      name: 'corpInfoNumber',
      path: 'number',
      component: corpInfoNumber,
      meta: {role: 'corp'}
    }]
  }, {
    name: 'shareNewsDetail',
    path: '/news-detail',
    component: newsDetail
  }, {
    name: 'test',
    path: '/test',
    component: test,
    children: [{
      name: 'test2',
      path: 'test2',
      component: test2,
      children: [{
        name: 'test3',
        path: 'test3',
        component: test3
      }]
    }]
  }, {
    name: 'reset',
    path: '/reset',
    component: reset
  }]
})

// 用户登录类型有两种 单位: corp  个人: user
router.beforeEach((to, from, next) => {
  if (!to.name) {
    next({name: 'home'})
    return
  }
  // 当企业登录时 home 切换为企业主页
  if (to.name === 'home' && store.state.userInfo && store.state.userInfo.role === 'corp') {
    next({name: 'corpHome'})
    return
  }
  // 需登录的路由
  if (to.meta && to.meta.role) {
    // 用户未登录
    if (!store.state.userInfo) {
      if (to.meta.role === 'corp') {
        next({name: 'corpLogin', query: {back: encodeURIComponent(to.path)}})
      } else {
        next({name: 'userLogin', query: {back: encodeURIComponent(to.path)}})
      }
      return
    }
    // 用户越权访问
    if (to.meta.role !== 'all' && store.state.userInfo.role !== to.meta.role) {
      next({name: 'home'})
      return
    }
    // 需要用户认证的路由
    if (to.meta.auth && Number(store.state.userInfo.auditStatus) !== 1) {
      MessageBox.confirm('您还未认证，是否前往认证？').then(() => {
        next({name: 'cert'})
      }).catch(() => {
        next(false)
      })
      return
    }
    if (to.meta.file && Number(store.state.userInfo.fileStatus) === 0) {
      next({name: 'myFile'})
      return
    }
  }
  next(true)
})

router.afterEach((to, fro) => {
  // 将用户最近使用过的8个功能保存为我的业务
  let service = findService(to.path)
  let myService = services[0].list
  if (service) {
    let index = myService.findIndex(item => item.link === service.link)
    if (index !== -1) {
      myService.unshift(myService.splice(index, 1)[0])
    } else {
      myService.unshift(service)
      myService.splice(8)
    }
    localStorage.setItem(STORAGE_TYPE.myService, JSON.stringify(myService))
  }
})

export default router
